<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Delete } from "@element-plus/icons-vue";
import axios from "axios";

// 科目映射函数
const mapSubject = (subjectId) => {
  const subjectMap = {
    1: 'AI智能应用开发(Java)',
    2: 'AI大模型开发(Python)',
    3: 'AI鸿蒙开发',
    4: 'AI大数据',
    5: 'AI嵌入式',
    6: 'AI测试',
    7: 'AI运维'
  };
  return subjectMap[subjectId] || '其他';
};

// 目标人群映射函数
const mapTarget = (targetId) => {
  const targetMap = {
    1: '小白学员',
    2: '中级程序员'
  };
  return targetMap[targetId] || '其他';
};

// 反向映射：名称到ID
const reverseMapSubject = (subjectName) => {
  const subjectMap = {
    'AI智能应用开发(Java)': 1,
    'AI大模型开发(Python)': 2,
    'AI鸿蒙开发': 3,
    'AI大数据': 4,
    'AI嵌入式': 5,
    'AI测试': 6,
    'AI运维': 7
  };
  return subjectMap[subjectName] || 1;
};

// 反向映射：目标人群到ID
const reverseMapTarget = (targetName) => {
  const targetMap = {
    '小白学员': 1,
    '中级程序员': 2
  };
  return targetMap[targetName] || 1;
};

// 格式化日期时间为Java LocalDateTime兼容格式
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 搜索条件
const searchForm = reactive({
  courseName: '',
  courseSubject: '',
  applicableGroup: ''
});

// 构建搜索参数
const buildSearchParams = () => {
  const params = {
    page: pagination.currentPage,
    pageSize: 10  // 固定每页显示10条数据
  };
  
  if (searchForm.courseName) {
    params.name = searchForm.courseName;
  }
  
  if (searchForm.courseSubject) {
    params.subject = reverseMapSubject(searchForm.courseSubject);
  }
  
  if (searchForm.applicableGroup) {
    params.target = reverseMapTarget(searchForm.applicableGroup);
  }
  
  return params;
};

// 课程列表数据
const courseList = ref([]);

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref('');

// 表单数据
const form = reactive({
  id: '',
  subject: '',
  name: '',
  price: '',
  group: '',
  description: '',
  createTime: '',
  updateTime: ''
});

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择课程学科', trigger: 'change' }],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须为非负数', trigger: 'blur' }
  ],
  group: [{ required: true, message: '请选择适用人群', trigger: 'change' }]
});

const formRef = ref(null);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
});

// 模拟课程数据
const mockCourses = [
  { id: 1, subject: 'Java', name: 'JavaSE基础', price: 598, group: '零基础', description: '主要面向零基础同学，深入讲解JavaSE核心知识点...', updateTime: '2025-05-21 08:50:08' },
  { id: 2, subject: 'Java', name: 'JavaEE进阶', price: 18000, group: '中级程序员', description: '主要面向有一定基础的同学，深入讲解JavaEE企业级开发...', updateTime: '2025-05-21 08:50:08' },
  { id: 3, subject: 'Java', name: 'Java基础班', price: 10000, group: '零基础', description: '主要面向零基础同学，深入讲解Java基础知识...', updateTime: '2025-05-21 08:50:08' },
  { id: 4, subject: 'Java', name: 'Java基础班', price: 10000, group: '零基础', description: '主要面向零基础同学，深入讲解Java基础知识...', updateTime: '2025-05-21 08:50:08' },
  { id: 5, subject: 'Java', name: 'Java基础班', price: 10000, group: '零基础', description: '主要面向零基础同学，深入讲解Java基础知识...', updateTime: '2025-05-21 08:50:08' },
  { id: 6, subject: 'Java', name: 'Java基础班', price: 10000, group: '中级程序员', description: '主要面向零基础同学，深入讲解Java基础知识...', updateTime: '2025-05-21 08:50:08' }
];

// 加载课程列表
const loadCourses = async () => {
  try {
    // 构建请求参数
    const params = buildSearchParams();
    
    // 调用API获取课程列表
    const response = await axios.get('/api/courses', { params });
    const data = response.data;
    
    if (data.code === 1) {
      // 处理原始数据，进行字段映射
      courseList.value = (data.data.rows || []).map(course => ({
        ...course,
        subject: mapSubject(course.subject),
        group: mapTarget(course.target)
      }));
      pagination.total = data.data.total || 0;
    } else {
      ElMessage.error('获取课程列表失败：' + data.message);
      courseList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取课程列表异常：', error);
    ElMessage.error('获取课程列表失败，请稍后重试');
    courseList.value = [];
    pagination.total = 0;
  }
};

// 搜索课程
const searchCourses = () => {
  pagination.currentPage = 1; // 重置到第一页
  loadCourses();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.courseName = '';
  searchForm.courseSubject = '';
  searchForm.applicableGroup = '';
  pagination.currentPage = 1; // 重置到第一页
  loadCourses(); // 重新加载课程列表
};

// 添加课程
const addCourse = () => {
  // 重置表单
  formRef.value?.resetFields();
  form.id = '';
  form.subject = '';
  form.name = '';
  form.price = '';
  form.group = '';
  form.description = '';
  
  // 设置对话框标题并显示
  dialogTitle.value = '添加课程';
  dialogVisible.value = true;
};

// 保存课程
const saveCourse = async () => {
  // 验证表单
  await formRef.value.validate();
  
  try {
    let response;
    
    // 判断是新增还是编辑
    if (!form.id) {
      // 新增课程
      response = await axios.post('/api/courses', {
        subject: reverseMapSubject(form.subject),
        name: form.name,
        price: Number(form.price),
        target: reverseMapTarget(form.group),
        description: form.description
      });
    } else {
      // 编辑课程 - 根据后端@PutMapping定义使用PUT方法
      response = await axios.put('/api/courses', {
        id: form.id,
        subject: reverseMapSubject(form.subject),
        name: form.name,
        price: Number(form.price),
        target: reverseMapTarget(form.group),
        description: form.description,
        createTime: form.createTime || formatDateTime(new Date()),
        updateTime: formatDateTime(new Date())
      });
    }
    
    const data = response.data;
    if (data.code === 1) {
      ElMessage.success(form.id ? '编辑课程成功' : '添加课程成功');
      dialogVisible.value = false;
      loadCourses(); // 重新加载课程列表
    } else {
      ElMessage.error((form.id ? '编辑课程失败：' : '添加课程失败：') + data.message);
    }
  } catch (error) {
    console.error(form.id ? '编辑课程异常：' : '添加课程异常：', error);
    ElMessage.error(form.id ? '编辑课程失败，请稍后重试' : '添加课程失败，请稍后重试');
  }
};

// 编辑课程
const editCourse = async (courseId) => {
  try {
    // 获取课程详情
    const response = await axios.get(`/api/courses/${courseId}`);
    const data = response.data;
    
    if (data.code === 1) {
      const course = data.data;
      // 填充表单数据
      form.id = course.id;
      form.subject = mapSubject(course.subject); // 显示名称
      form.name = course.name;
      form.price = course.price;
      form.group = mapTarget(course.target); // 显示名称
      form.description = course.description;
      form.createTime = course.createTime; // 保存创建时间，用于更新时传递
      
      // 设置对话框标题并显示
      dialogTitle.value = '编辑课程';
      dialogVisible.value = true;
    } else {
      ElMessage.error('获取课程详情失败：' + data.message);
    }
  } catch (error) {
    console.error('获取课程详情异常：', error);
    ElMessage.error('获取课程详情失败，请稍后重试');
  }
};

// 删除课程
const deleteCourse = async (courseId) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确定要删除该课程吗？此操作不可撤销。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 调用API删除课程
    const response = await axios.delete(`/api/courses/${courseId}`);
    const data = response.data;
    
    if (data.code === 1) {
      ElMessage.success('删除课程成功');
      loadCourses(); // 重新加载课程列表
    } else {
      ElMessage.error('删除课程失败：' + data.message);
    }
  } catch (error) {
    // 如果是用户取消操作，不显示错误
    if (error.message !== 'cancel') {
      console.error('删除课程异常：', error);
      ElMessage.error('删除课程失败，请稍后重试');
    }
  }
};

// 分页变化处理
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  loadCourses(); // 根据页码重新加载数据
};

// 页面大小变化处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1; // 重置到第一页
  loadCourses(); // 根据页面大小重新加载数据
};

// 组件挂载时加载数据
onMounted(() => {
  loadCourses();
});
</script>

<template>
  <div class="course-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form inline :model="searchForm">
        <el-form-item label="课程名称：">
          <el-input
            v-model="searchForm.courseName"
            placeholder="请输入"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="课程学科：">
          <el-select
            v-model="searchForm.courseSubject"
            placeholder="请选择"
            style="width: 180px;"
          >
            <el-option label="AI智能应用开发(Java)" value="AI智能应用开发(Java)" />
            <el-option label="AI大模型开发(Python)" value="AI大模型开发(Python)" />
            <el-option label="AI鸿蒙开发" value="AI鸿蒙开发" />
            <el-option label="AI大数据" value="AI大数据" />
            <el-option label="AI嵌入式" value="AI嵌入式" />
            <el-option label="AI测试" value="AI测试" />
            <el-option label="AI运维" value="AI运维" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用人群：">
          <el-select
            v-model="searchForm.applicableGroup"
            placeholder="请选择"
            style="width: 180px;"
          >
            <el-option label="小白学员" value="小白学员" />
            <el-option label="中级程序员" value="中级程序员" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCourses">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 添加课程按钮 -->
    <div class="add-button-container">
      <el-button type="primary" @click="addCourse">+ 添加课程</el-button>
    </div>

    <!-- 课程列表表格 -->
    <div class="table-container">
      <el-table :data="courseList" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="subject" label="课程学科" width="100" />
        <el-table-column prop="name" label="课程名称" width="150" />
        <el-table-column prop="price" label="价格(元)" width="100">
          <template #default="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="group" label="适用人群" width="120" />
        <el-table-column prop="description" label="课程介绍" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.description }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后更新时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              text
              size="small"
              @click="editCourse(scope.row.id)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              text
              size="small"
              @click="deleteCourse(scope.row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程学科" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择">
            <el-option label="AI智能应用开发(Java)" value="AI智能应用开发(Java)" />
            <el-option label="AI大模型开发(Python)" value="AI大模型开发(Python)" />
            <el-option label="AI鸿蒙开发" value="AI鸿蒙开发" />
            <el-option label="AI大数据" value="AI大数据" />
            <el-option label="AI嵌入式" value="AI嵌入式" />
            <el-option label="AI测试" value="AI测试" />
            <el-option label="AI运维" value="AI运维" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input
            v-model.number="form.price"
            type="number"
            placeholder="请输入"
            min="0"
          />
        </el-form-item>
        <el-form-item label="适用人群" prop="group">
          <el-select v-model="form.group" placeholder="请选择">
            <el-option label="小白学员" value="小白学员" />
            <el-option label="中级程序员" value="中级程序员" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程介绍">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ pagination.total }} 记录 第 {{ pagination.currentPage }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          :page-size="10"
          layout="prev, pager, next, jumper"
          :total="pagination.total"
          @current-change="handleCurrentChange"
          @prev-click="handleCurrentChange"
          @next-click="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.course-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.add-button-container {
  margin-bottom: 16px;
}

.table-container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 表格样式优化 */
.el-table {
  --el-table-header-bg-color: #f5f7fa;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}



/* 对话框样式优化 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
